const entitiesToUtf16 = (str) => {
	return str.replace(/&#(\d+);/g, function(match, dec) {
		let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;
		let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;
		return String.fromCharCode(H, L);
	});
}

/* 正数 可以是小数 */
const isPattern = (str) => {
	console.log(str);
	var posPattern = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
	if(posPattern.test(str)) {
		return true;
	}else {
		return false;
	}
}

/**
 * 计算时间差
 */
const timeFn = (d1) => { //di作为一个变量传进来
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = new Date(d1.replace(/-/g, "/")); //将-转化为/，使用new Date
	var dateEnd = new Date(); //获取当前时间
	var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
	var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
	var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	let msg = '刚刚';
	if (dayDiff == 0 && hours == 0) { // 此时为分钟
		if (minutes > 0) {
			msg = minutes + '分钟前';
		} else {
			msg = '1分钟前';
		}
	} else if (dayDiff == 1) {
		msg = dayDiff + '天前';
	} else if (dayDiff == 0 && hours > 0) {
		msg = hours + '小时前';
	} else if (dayDiff > 1) {
		msg = d1;
	}
	return msg;
}
/**
 * 不自动补0
 */
const getDateNoZero = (now) => {
	var year = now.getFullYear(); //获取四位数年数
	var month = now.getMonth() + 1;
	var date = now.getDate();
	var s = year + "-" + month + "-" + date;
	return s;
}

/**
 * 日期加减
 */
const calculateDate = (oldDate, num) => {
	let time = new Date().setDate(oldDate.getDate() + parseInt(num));
	let date1 = new Date(time);
	return getNowTime(date1, 'yyyy-MM-dd');
}

/**
 * 获取当前时间
 */
const getNowTime = (dateVal, fmt) => {
	var o = {
		"M+": dateVal.getMonth() + 1, //月份 
		"d+": dateVal.getDate(), //日 
		"h+": dateVal.getHours(), //小时 
		"m+": dateVal.getMinutes(), //分 
		"s+": dateVal.getSeconds(), //秒 
		"q+": Math.floor((dateVal.getMonth() + 3) / 3), //季度 
		"S": dateVal.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (dateVal.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)));
		}
	}
	return fmt;
}

/**
 * 获取当前周
 */
const getWeek = (dateVal) => {
	let days = dateVal.getDay();
	switch (days) {
		case 1:
			days = '星期一';
			break;
		case 2:
			days = '星期二';
			break;
		case 3:
			days = '星期三';
			break;
		case 4:
			days = '星期四';
			break;
		case 5:
			days = '星期五';
			break;
		case 6:
			days = '星期六';
			break;
		case 0:
			days = '星期日';
			break;
	}
	return days;
}

export default {
	timeFn,
	getNowTime,
	getDateNoZero,
	calculateDate,
	getWeek,
	entitiesToUtf16,
	isPattern
}
